package com.application.fabric.test.ca_become;
import org.hyperledger.fabric.gateway.*;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric.sdk.security.CryptoSuiteFactory;
import org.hyperledger.fabric_ca.sdk.HFCAClient;

import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Properties;

public class 读取用户内容 {
    public static void main(String[] args) throws Exception{
//        CertificateFactory cf = CertificateFactory.getInstance("X.509");
//        String filepath = publichava.class.getClassLoader().getResource("templates/appUser.id").getPath();
//        /* privatepath = c1.getResource("templates/rsa.pri").getPath();*/
//        /*.getClass().getClassLoader().getResource("templates/appUser.id").getPath();*/
//        FileInputStream in = new FileInputStream(filepath);
//        Certificate c = cf.generateCertificate(in);
//        PublicKey publicKey = c.getPublicKey();
//        String key = Base64.getEncoder().encodeToString(publicKey.getEncoded());
//        System.out.println(key);
        Properties props = new Properties();
        props.put("pemFile","src/main/resources/crypto-config/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem");
        props.put("allowAllHostNames","true");
        HFCAClient caClient = HFCAClient.createNewInstance("https://localhost:7054", props);
        CryptoSuite cryptoSuite = CryptoSuiteFactory.getDefault().getCryptoSuite();
        caClient.setCryptoSuite(cryptoSuite);
        Wallet wallet = Wallets.newFileSystemWallet(Paths.get("src/main/java/com/application/fabric/fabriccontrol/wallet"));
        X509Identity adminIdentity = (X509Identity)wallet.get("admin");
//        System.out.println(adminIdentity.getCertificate());
        System.out.println(adminIdentity.getCertificate());
        X509Certificate cer = adminIdentity.getCertificate();
        String str = Base64.getEncoder().encodeToString(cer.getEncoded());
        System.out.println(str);
//        PrivateKey prikey = adminIdentity.getPrivateKey();
//        String key = Base64.getEncoder().encodeToString(prikey.getEncoded());
//        System.out.println(key);

        /*破坏性md5*/
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digestBytes = md.digest(str.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : digestBytes) {
            sb.append(String.format("%02x", b & 0xff));
        }
//        System.out.println("MD5 hash: " + sb.toString());
    }
}
